<?php

namespace app\admin\controller;


use think\Controller;
use think\Validate;
use think\Db;
use think\Session;

class Index extends Controller
{
    //计算错误次数
    protected function checkPassWrongTime($uid, $min=30, $wTime=3)
    {
 
        if ( empty($uid) ) {
 
            throw new \Exception("第一个参数不能为空");
 
        }
 
        $time = time();
        $prevTime = time() - $min*60;
        // dump($time);
        // dump($prevTime);
        //pass_wrong_time_status代表用户输错了密码
        $data = Db::name('user_login_info')->where('uid',$uid)->where('pass_wrong_time_status','2')->select();
        // dump($data);die;
        // $sql = "select * from user_login_info where uid={$uid} and pass_wrong_time_status=2 and UNIX_TIMESTAMP(logintime) between $prevTime and $time and ipaddr=$ip";
 
        // $stmt = $this->pdo->prepare($sql);
 
        // $stmt->execute();
 
        // $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
 
 
        //统计错误次数
        $wrongTime = count($data);
        // dump($wrongTime);die;
        //判断错误次数是否超过限制次数
        if ( $wrongTime >= $wTime ) {
            return false;
        }else{
 
            return $wrongTime;
        }
    }

    //记录密码输出信息
    protected function recordPassWrongTime($uid)
    {
 
        //ip2long()函数可以将IP地址转换成数字
        // $ip = ip2long( $_SERVER['REMOTE_ADDR'] );
 
        $time = time();
        $data = [
                'uid'=>$uid,
                'logintime'=>$time,
                'pass_wrong_time_status'=>'2'
                ];
        Db::name('user_login_info')->insert($data);

        // $sql = "insert into user_login_info(uid,ipaddr,logintime,pass_wrong_time_status) values($uid,$ip,'{$time}',2)";
 
 
        // $stmt = $this->pdo->prepare($sql);
 
        // $stmt->execute();
    }

    //查登录用户的所有权限
    protected function selectNode($uid='')
    {
        //查权限
        //1.查角色 带着id去查
        //select * from zzz_user_role ur left join zzz_role r on ur.rid = r.id where ur.uid=10;

        $myrole = Db::name('user_role ur')
                ->join('role r','ur.rid=r.id','LEFT')
                ->where('ur.uid',$uid)
                ->select();
        // dump($myrole);die;
        if(empty($myrole)){
            $this->error('您没有任何角色');
        }
        //拿到该用户所有角色ID
        $role_ids = [];
        foreach($myrole as $k => $v){
            $role_ids [] = $v['rid'];
        }
        // dump($role_ids);die;
        $str_role = implode(',',$role_ids);
        //带着id们去查权限
        $mynode = Db::name('role_node rn')
                ->join('node n','rn.nid=n.id','LEFT')
                ->where('rn.rid','exp','in ('.$str_role.')')
                ->select();
        // dump($mynode);die;
        //处理mynode 去重
        $last = [];
       foreach($mynode as $k => $v){

            if(isset($last[$v['id']])){
                continue;
            }else{
                $last[$v['id']] = $v;
                unset($last[$v['id']]['rid']);
                unset($last[$v['id']]['nid']);

            }
       }
       // dump($last);die;
       foreach($last as $k=> $v){
            $lastnode[$k] = $v['mname'].'/'.$v['aname'];
       }
       // dump($lastnode);die;
            return $lastnode;
    }

    //存用户登录信息
    protected function userInfo($data)
    {
        $user = Db::name('user')->where('name',$data['name'])->find();;
        if (empty($user)) {
            $this->error('您的账号不存在','/admin');
        }
        // dump($user);die;
        $num = $this->checkPassWrongTime($user['id']);
        // dump($num);die;
        if ($num===false) {
            $res = Db::name('user_login_info')->where('uid',$user['id'])->where('pass_wrong_time_status','2')->field('logintime')->order('logintime')->select();
            $login = $res['0']['logintime'];
            $lefttime = floor($login+1800-time())/60;
            // dump($lefttime);die;
            if ($login + 1800 > time()) {
                $this->error('密码输错3次,账号已被锁定,请'.$lefttime.'分钟后重试','/admin');
            }
            //删除次数
            Db::name('user_login_info')->where('uid',$user['id'])->delete();
        }
        // dump($num);die;
        // 密码判断 错误
        $data['userpass'] = sha1($data['userpass']);
        
        if ($data['userpass']!=$user['userpass']) {
            // 添加次数
            $this->recordPassWrongTime($user['id']);
            $num = $num+1;
            $this->error('密码输错'.$num.'次','/admin');
        }

        Db::name('user_login_info')->where('uid',$user['id'])->delete();
        //存session 
        $lastnode = $this->selectNode($user['id']);
        Session::set('admin.name',$user['name'],'think');
        Session::set('admin.id',$user['id'],'think');
        $sess = Session::set('admin.node',$lastnode,'think');
        
        return true;
    }

    /**
     * 后台登录页面
     * @return \think\response\View
     */
    public function index()
    {
        return view('/index/login');
    }

    /**
     * 后台登录处理
     * @return \think\response\View
     */
    public function logindo()
    {
        $data = input('post.');

        // dump($data);die;
        $rule =['name'  => 'require|regex:/^[_0-9a-zA-Z]{6,16}$/',
                'userpass' => 'require|regex:/^[_0-9a-zA-Z]{6,16}$/'
                ];

        $message  =[
            'name.require' => '账号必须填',
            'name.regex'     => '账号6-16位数字字母或者下划线',
            'userpass.require'  => '密码必须填',
            'userpass.regex'=>'密码6-16位数字字母或者下划线'
            ];

        $validate = new Validate($rule,$message);
        $result   = $validate->check($data);

        // dump($result);die;
        if($result){
            if($this->userInfo($data)){
                
                return view('main/index');
            }

        }else{
            $this->error($validate->getError());
        }

        // $this->redirect('admin/main/index');
    }

    /**
     * 后台登出处理
     * @return \think\response\View
     */
    public function logout()
    {   
        Session::delete('admin');
        return view('index/login');
        
    }

}
